package com.imon.web.codesphere.resources;

import java.util.HashMap;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.imon.web.codesphere.data.FileSource;

@Path("/sourceview")
@Component
public class SourceViewResource extends ResourceBase {

	private static final Log LOG = LogFactory.getLog(SourceViewResource.class);

	@GET
	@Path("/{revision}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getSource(@PathParam("revision") final long revision, @QueryParam("file") final String filename) {
		LOG.debug(String.format("getSource(%s, %s)", revision, filename));

		final FileSource fileSource = getDatabase().loadSingle(FileSource.class, new HashMap<String, Object>() {
			{
				put("fileUrl =", filename);
				put("revision <=", revision);
			}
		}, "-revision");

		if (fileSource == null) {
			return Response.status(Status.NOT_FOUND).build();
		}

		return Response.ok(getJsonParser().getJson(fileSource)).build();
	}
}
